
//
//  ChongZhiVController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/7.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "ChongZhiVController.h"
#import "PayWayCell.h"

#import "PayResultView.h"//支付结果视图
#import "PayWayModel.h"



@interface ChongZhiVController ()<UITableViewDelegate, UITableViewDataSource,payResultBackBtnDelegate>
{
    NSString *payWayID;//充值方式
    NSString *moenyNumStr;//充值的钱数
}
@property (nonatomic, strong)NSArray *imageA;
@property (nonatomic, strong)NSArray *titleA;
@property (nonatomic, strong)NSArray *detailTileA;
@property (nonatomic, strong)PayResultView *payResultView;
@property (nonatomic, strong)NSMutableArray *dataArray;


@end

@implementation ChongZhiVController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_payResultView) {
        [_payResultView removeFromSuperview];
    }
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    [self getMyBlanace];//获取我的余额
}
#pragma mark 获取我的余额
- (void)getMyBlanace {
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest getWithURLString:POST(Shop_PersonalGetUserBalance) parameters:parameDic success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"获取余额出错"];
            return ;
        }
        NSDictionary *tempD = responseObject[@"data"];
        if (![[NSString stringWithFormat:@"%@",tempD[@"code"]] isEqualToString:@"0"]) {
            [MBProgressHUD showText:tempD[@"msg"]];
            return;
        }
        
        
        _moneyLB.text = [NSString stringWithFormat:@"%@元",responseObject[@"data"][@"info"][@"balance"]];
        
        
        
        
    } failure:^(NSError *error) {
        
    }];
    
    
    
    [_moneyTF addTarget:self action:@selector(handleText:) forControlEvents:(UIControlEventEditingChanged)];
    
}
- (void)handleText:(UITextField *)text {
    moenyNumStr = text.text;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataArray = [NSMutableArray array];
    payWayID = @"";
    moenyNumStr = @"";
    [self configureNaBar];
    [self getChongZhiPayWay];
    _imageA = @[@"weixin",@"zhifubao",@"yinlian"];
    _titleA = @[@"微信支付",@"支付宝支付",@"银联支付"];
    _detailTileA = @[@"推荐安装微信5.0及以上版本的使用",@"推荐有支付宝账户的用户使用",@"推荐有银行卡的用户使用"];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = kSpNone;
    [_tableView registerNib:[UINib nibWithNibName:@"PayWayCell" bundle:nil] forCellReuseIdentifier:@"PayWayCell"];
    
    
    
    
}

- (void)configureNaBar {
    self.navigationItem.title = @"充值";
    //设置导航栏按钮的边距
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(handleBackAxtion) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    
    
    
}
- (void)handleBackAxtion {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 65;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PayWayCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PayWayCell"];
    cell.selectionStyle = kSeNone;
    PayWayModel *model = self.dataArray[indexPath.row];
    [cell.logoV sd_setImageWithURL:[NSURL URLWithString:model.logo] placeholderImage:[UIImage imageNamed:@"quetu"]];
    cell.titleLB.text = model.name;
    cell.contengLB.text = model.desc;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PayWayModel *model = self.dataArray[indexPath.row];
    payWayID = model.Id;
}


#pragma mark  －＝－－＝－＝－确认充值按钮的点击事件
- (IBAction)payMoneyBtnAction:(UIButton *)sender {
    if (payWayID.length == 0) {
        [MBProgressHUD showText:@"请选择充值方式"];
        return;
    };
    if ([self isBlankString:moenyNumStr] == YES) {
        [MBProgressHUD showText:@"请输入充值金额"];
        return;
    }
    
    
    
    
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"amount":moenyNumStr,@"payment_id":payWayID,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest postWithURLString:POST(Shop_PersonalOnline_recharge_save) parameters:parameDic success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"插入订单出错"];
            return ;
        }
        NSDictionary *tempD = responseObject[@"data"];
        
        if (![[NSString stringWithFormat:@"%@",tempD[@"code"]] isEqualToString:@"0"]) {
            [MBProgressHUD showText:tempD[@"msg"]];
            return;
        }
        
        NSString *str = responseObject[@"data"][@"recharge_no"];//获取订单号

        CGFloat moenyX = [moenyNumStr floatValue] *100;
        //更新状态
         NSDictionary *parameDic2 = @{@"type":@"alipay",@"total_fee":[NSString stringWithFormat:@"%.f",moenyX],@"order_no":str};
        [HttpRequest postWithURLString:POST(Pay_NotifyText) parameters:parameDic2 success:^(id responseObject) {
            /*
            if ([responseObject[@"ret"] intValue] != 200) {
                [MBProgressHUD showText:@"在线充值出错"];
                return ;
            }
            NSDictionary *tempD = responseObject[@"data"];
            
            if (![[NSString stringWithFormat:@"%@",tempD[@"code"]] isEqualToString:@"0"]) {
                [MBProgressHUD showText:tempD[@"msg"]];
                return;
            }*/
            
            if (_payResultView) {
                [_payResultView removeFromSuperview];
            }
            _payResultView = [[PayResultView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
            _payResultView.delegate = self;
            _payResultView.imageStr = @"chongzhichengg";
            _payResultView.payResultStr = @"充值成功";
            _payResultView.detailStr = @"已成功充值X元到你的钱包";
            [[UIApplication sharedApplication].keyWindow addSubview:_payResultView];
            
            
        } failure:^(NSError *error) {
            
        }];
        
        
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)payBackAction:(UIButton *)sender {
    if (_payResultView) {
        [_payResultView removeFromSuperview];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark   －＝－＝－＝－＝－获取充值方式－＝
- (void)getChongZhiPayWay {
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"type":@"online_recharge",@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
   
    
    [HttpRequest getWithURLString:POST(Pay_PayGetPayment) parameters:parameDic success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"获取支付方式出错"];
            return ;
        }
        
        NSDictionary *tempD = responseObject[@"data"];
        
        if (![[NSString stringWithFormat:@"%@",tempD[@"code"]] isEqualToString:@"0"]) {
            [MBProgressHUD showText:tempD[@"msg"]];
            return;
        }
        _dataArray =[PayWayModel mj_objectArrayWithKeyValuesArray:tempD[@"list"]];
        
        [self.tableView reloadData];
        
        
    } failure:^(NSError *error) {
        
    }];
}
//判断一个字符串是否为空
- (BOOL) isBlankString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        
        return YES;
        
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        return YES;
        
    }
    
    return NO;
    
}



@end
